package cn.itcast.Servlet;

import cn.itcast.domain.User;
import cn.itcast.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 更改cakedb数据库中的yue
 */
@WebServlet("/chongzhiServlet")
public class chongzhiServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn=null;
        PreparedStatement pst=null;
        HttpSession session = request.getSession();
        //获取当前的money
        double money = 0;
        try {
            money = Double.parseDouble(request.getParameter("money"));
        } catch (NumberFormatException e) {
            //如果money输入的不是一个数字会报错
            response.getWriter().write("充值失败,请输入有效数字");
            response.getWriter().write("<a href='shopingcenter.jsp'>商城界面</a>\n");
            e.printStackTrace();
            //终止当前Servlet
            return;
        }
        try {
            conn=JDBCUtils.getConnection();
            User user= (User) session.getAttribute("user");
            if (user!=null){
                money= user.getYue()+money;
                String sql="update user set yue = ? where username = ? and password = ?";
                pst=conn.prepareStatement(sql);
                pst.setDouble(1,money);
                pst.setString(2,user.getName());
                pst.setString(3,user.getPassword());
                //充值余额
                pst.executeUpdate();
                user.setYue(money);
                session.setAttribute("user",user);
                Cookie cookie=new Cookie("autologin",user.getName()+"-"+user.getPassword()+"-"+user.getYue());
                response.addCookie(cookie);
                //跳转回shopingcenter页面
                response.sendRedirect(request.getContextPath()+"/shopingcenter.jsp");
            }
        } catch (SQLException e) {
            //如果错误
            response.getWriter().write("充值失败,发生未知错误");
            response.getWriter().write("<a href='shopingcenter.jsp'>商城界面</a>\n");
            e.printStackTrace();
        }finally {
            JDBCUtils.close(conn,pst);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
